import socket
import binascii

# 构建报文函数
def build_message():
    # 定义字段数据
    length_string = "256"          # 电文长度
    tele_no = 'L2DS01'    # 电文号
    coil_no = '1234567890123456'  # 钢卷号
    length_val = 123.456  # 长度
    width_val = 123.42     # 宽度
    thickness_val = 123.4  # 厚度
    steel_grade = 'Q235B456'  # 出钢记号
    sorting_grade = 'A2'   # 分选度
    work_order_no = 'WO12345670'  # 生产合同号
    order_quality = 'Q235B7850412qws235sa'  # 钢种牌号
    final_use = '1234'  # 最终用途
    final_user = 'user01'  # 最终用户代码
    dummy = '12'   # 过渡卷标志
    surf_struc_code = 'ABC1'  # 表面结构
    post_proc = '1235'  # 后处理方式
    
    # 转换数据为字节
    length_bytes = length_string.ljust(4, ' ').encode('ascii')
    tele_no_bytes = tele_no.ljust(6, ' ').encode('ascii')  # 6 字节
    coil_no_bytes = coil_no.ljust(16, ' ').encode('ascii')  # 16 字节

    # 将浮动小数转为整数并填充为6个字节
    length_val_int = int(length_val * 1000)  # 去掉小数点并转为整数
    width_val_int = int(width_val * 1000)  # 去掉小数点并转为整数
    thickness_val_int = int(thickness_val * 1000)  # 去掉小数点并转为整数
    length_val_bytes = f"{length_val_int:08d}".encode('ascii')  # 转换为8字节整数
    width_val_bytes = f"{width_val_int:06d}".encode('ascii')  # 转换为6字节整数
    thickness_val_bytes = f"{thickness_val_int:06d}".encode('ascii')  # 转换为6字节整数
    
    steel_grade_bytes = steel_grade.ljust(8, ' ').encode('ascii')  # 8 字节
    sorting_grade_bytes = sorting_grade.ljust(2, ' ').encode('ascii')  # 2 字节
    work_order_no_bytes = work_order_no.ljust(10, ' ').encode('ascii')  # 10 字节
    order_quality_bytes = order_quality.ljust(20, ' ').encode('ascii')  # 20 字节
    final_use_bytes = final_use.ljust(4, ' ').encode('ascii')  # 4 字节
    final_user_bytes = final_user.ljust(6, ' ').encode('ascii')  # 6 字节
    dummy_bytes = dummy.ljust(2, ' ').encode('ascii')  # 2 字节
    surf_struc_code_bytes = surf_struc_code.ljust(4, ' ').encode('ascii')  # 4 字节
    post_proc_bytes = post_proc.ljust(4, ' ').encode('ascii')  # 4 字节

    # 拼接所有字段为最终报文
    message = (length_bytes + tele_no_bytes + coil_no_bytes + 
               length_val_bytes + width_val_bytes + thickness_val_bytes +
               steel_grade_bytes + sorting_grade_bytes +
               work_order_no_bytes + order_quality_bytes + 
               final_use_bytes + final_user_bytes + dummy_bytes +
               surf_struc_code_bytes + post_proc_bytes)
    message = message.ljust(256, b' ')
    # 打印报文的十六进制表示
    print(f"Sent (Hex): {binascii.hexlify(message).decode('ascii')}")
    return message

# 发送报文
def send_message():
    # 创建 TCP socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('127.0.0.1', 5001))  # 连接到服务器

    # 构建报文
    message = build_message()

    # 发送报文
    s.sendall(message)
    print(f"Sent: {message}")

    # 接收响应
    data = s.recv(1024)
    print(f"Received: {data.decode('utf-8')}")

    # 关闭连接
    s.close()

# 执行发送
#send_message()
build_message()
